package io.renren.modules.tag.utils;

import java.util.HashMap;
import java.util.Map;

public class Example {
    public static void main(String[] args) {
        String boundSql = getSql();

        // 输出绑定后的 SQL 查询语句
        System.out.println(boundSql);
    }

    private static String getSql() {
        String sql = "WITH (  SELECT tagbitmap from (select * from labelinfo.label_tag_bitmap_all where subject = 'ztk_ryztxxb') where tagvalue = ? ) AS tag1, ( SELECT tagbitmap from (select * from labelinfo.label_tag_bitmap_all where subject = 'ztk_ryztxxb') where tagvalue = ? ) AS tag2, ( SELECT tagbitmap from (select * from labelinfo.label_tag_bitmap_all where subject = 'ztk_ryztxxb') where tagvalue = ? ) AS tag3, ( SELECT tagbitmap from (select * from labelinfo.label_tag_bitmap_all where subject = 'ztk_ryztxxb') where tagvalue = ? ) AS tag4 select bitmapToArray(bitmapOr(bitmapAnd(tag1, tag2),bitmapAnd(tag3, tag4))) as customer";

        // 创建要绑定的参数
        Map<Integer, Object> params = new HashMap<>();
        params.put(1, "青年");
        params.put(2, "境外旅游");
        params.put(3, "频繁出行");
        params.put(4, "去往敏感地");

        // 将参数绑定到 SQL 查询语句中
        String boundSql = bindSqlParams(sql, params);
        return boundSql;
    }

    private static String bindSqlParams(String sql, Map<Integer, Object> params) {
        // 将 SQL 查询语句中的占位符 ? 替换为对应的参数值
        StringBuilder sb = new StringBuilder();
        int i = 0;
        int j = 1;
        while (i < sql.length()) {
            int idx = sql.indexOf('?', i);
            if (idx == -1) {
                sb.append(sql.substring(i));
                break;
            } else {
                sb.append(sql.substring(i, idx));
                Object paramValue = params.get(j++);
                if (paramValue == null) {
                    sb.append("null");
                } else if (paramValue instanceof Number || paramValue instanceof Boolean) {
                    sb.append(paramValue);
                } else {
                    sb.append("'");
                    sb.append(paramValue.toString().replace("'", "''"));
                    sb.append("'");
                }
                i = idx + 1;
            }
        }
        return sb.toString();
    }
}
